package com.seteam.collabcrossword;

import au.com.bytecode.opencsv.CSVReader;
import com.seteam.collabcrossword.exceptions.CollabCrosswordException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * This class provides a method to read a given CSV file with clues and solutions,
 * and generate a map of clue IDs and {@link Clue}s.
 */
public class FileReader {
    private final Logger logger = LoggerFactory.getLogger(FileReader.class);
    private Resource resource;
    private static final int STATEMENT_INDEX = 0;
    private static final int ID_INDEX = 3;
    private static final int ANSWER_INDEX = 1;
    private static final int ABSOLUTE_ID_INDEX = 2;

    /**
     * Constructor
     */
    public FileReader() {

    }

    /**
     * Takes a CSV file and generates a map of clue IDs and clues
     *
     * @param file the file with clues and solutions
     * @return a map of clue IDs and clues
     * @throws IOException              if there is an error in reading the file
     * @throws CollabCrosswordException if are errors in creating any instance of {@link Clue}
     */
    public Map<Integer, Clue> getCluesMap(final String file) throws IOException, CollabCrosswordException {
        Map<Integer, Clue> result = new LinkedHashMap<Integer, Clue>();
        resource = new ClassPathResource(file + ".csv");
        final InputStream inputStream = resource.getInputStream();
        final InputStreamReader streamReader = new InputStreamReader(inputStream);
        final CSVReader csvReader = new CSVReader(streamReader);

        String[] nextLine;
        Clue clue = null;
        int count = 0;
        while ((nextLine = csvReader.readNext()) != null) {
            clue = new Clue(Integer.parseInt(nextLine[ID_INDEX]),
                    nextLine[STATEMENT_INDEX], nextLine[ANSWER_INDEX]);
            clue.setAbsoluteID(Integer.parseInt(nextLine[ABSOLUTE_ID_INDEX]));
            result.put(count++, clue);
        }

        return result;
    }
}
